import React, { useEffect, useState } from 'react';
import { NavBar, Result } from 'antd-mobile';
import { useNavigate, useLocation } from 'react-router-dom';
import axios from '../../axios';
import './Com/PaymentSuccess.css';

const PaymentSuccess: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [countdown, setCountdown] = useState(5);
  const [status, setStatus] = useState('处理中...');

  useEffect(() => {
    // 从URL参数或localStorage获取支付信息
    const urlParams = new URLSearchParams(location.search);
    const outTradeNo = urlParams.get('out_trade_no') || localStorage.getItem('lastOutTradeNo');
    const userId = localStorage.getItem('yonghuId');
    const orderId = localStorage.getItem('lastOrderId');

    console.log('PaymentSuccess页面接收到的参数:', {
      outTradeNo,
      userId,
      orderId,
      urlParams: Object.fromEntries(urlParams.entries())
    });

    if (outTradeNo && userId && orderId) {
      // 立即查询并更新支付状态
      updatePaymentStatus(userId, orderId, outTradeNo);
    } else {
      console.log('缺少必要参数，无法更新支付状态');
      setStatus('缺少支付参数，请检查支付结果');
    }

    // 倒计时
    const countdownTimer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(countdownTimer);
          navigate('/my/order');
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(countdownTimer);
  }, [navigate, location]);

  const updatePaymentStatus = async (userId: string, orderId: string, outTradeNo: string) => {
    try {
      setStatus('正在更新支付状态...');
      
      const response = await axios.post('/hy/yonghu/check-payment-status', {
        userId,
        orderId,
        outTradeNo
      });

      if (response.data.code === 200) {
        setStatus('支付状态更新成功');
      } else {
        setStatus('支付状态更新失败');
      }
    } catch {
      setStatus('支付状态更新失败');
    }
  };

  return (
    <div className="payment-success-page">
      <NavBar onBack={() => navigate(-1)}>支付结果</NavBar>
      
      <div className="success-container">
        <Result
          status="success"
          title="支付成功"
          description={`${countdown}秒后自动跳转到订单页面...`}
        />
      </div>
    </div>
  );
};

export default PaymentSuccess; 